package dictcn.com.activity;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv1.OAuthV1;
import com.tencent.weibo.oauthv1.OAuthV1Client;
import com.tencent.weibo.webview.OAuthV1AuthorizeWebView;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.AccountAPI;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.util.Utility;

import dictcn.com.R;
import dictcn.com.control.AccessQqTokenKeeper;
import dictcn.com.control.AccessSinaTokenKeeper;
import dictcn.com.model.AccessQqUserInfo;
import dictcn.com.model.AccessSinaUserId;
import dictcn.com.model.AccessSinaUserInfo;

public class ShareSend extends Activity {

	private EditText edit_share_content;
	private ImageView img_delete;
	private TextView txt_send_count;
	private Button btn_send;
	private ImageView img_sharesend_qqzone;
	private ImageView img_sharesend_sina;
	private ImageView img_sharesend_qqweibo;
	private ImageButton imgbtn_sharesend_back;
	
	
	private Button btn_sharesend_email;
	private Button btn_sharesend_sms;
	private Button btn_sharesend_weixin;
	private Button btn_sharesend_renren;
	
	private static OAuthV1 oauth;	
	private static Weibo mWeibo;
	private static Oauth2AccessToken accessToken;
	
	//响应sina微博认证的hanler，sina要，腾讯不用
	private Handler myHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:
				Toast.makeText(ShareSend.this, "连接成功！", Toast.LENGTH_SHORT).show();
				setSinaMap(true);
				break;
			case 2:
				Toast.makeText(ShareSend.this, "发布成功！", Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(ShareSend.this, "信息分享失败，网络连接失败！", Toast.LENGTH_SHORT).show();
				break;
			case 4:
				Toast.makeText(ShareSend.this, "网络连接失败！", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share_send);
		
		initView();
	}
	
	//初始化组件
	private void initView(){
		
		edit_share_content=(EditText)findViewById(R.id.edit_share_send);
		btn_send=(Button)findViewById(R.id.btn_share_send);
		txt_send_count=(TextView)findViewById(R.id.txt_send_count);
		img_sharesend_qqzone=(ImageView)findViewById(R.id.img_sharesend_qqzone);
		img_sharesend_sina=(ImageView)findViewById(R.id.img_sharesend_sina);
		img_sharesend_qqweibo=(ImageView)findViewById(R.id.img_sharesend_qqweibo);
		img_delete=(ImageView)findViewById(R.id.img_delete);
		imgbtn_sharesend_back=(ImageButton)findViewById(R.id.imgBtn_sharesend_back);
		btn_sharesend_email=(Button)findViewById(R.id.btn_sharesend_email);
		btn_sharesend_renren=(Button)findViewById(R.id.btn_sharesend_renren);
		btn_sharesend_sms=(Button)findViewById(R.id.btn_sharesend_sms);
		btn_sharesend_weixin=(Button)findViewById(R.id.btn_sharesend_weixin);
	
		imgbtn_sharesend_back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ShareSend.this.finish();
			}
		});
		
		//删除图标点击事件
		img_delete.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				edit_share_content.setText("");
				txt_send_count.setText("0/240");
			}
		});
		
		//发布按钮点击事件
		btn_send.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				//没有响应的账号绑定？
				if((!AccessQqUserInfo.readQqUserShareBind(ShareSend.this))&&
						(!AccessSinaUserInfo.readUserInfoShareBind(ShareSend.this))){
					Toast.makeText(ShareSend.this, "请选择要发布的账号", Toast.LENGTH_SHORT).show();			
				}
				else {
					//腾讯微博账号绑定了
					if(AccessQqUserInfo.readQqUserShareBind(ShareSend.this)){	
		
						String str=edit_share_content.getText().toString().trim();
						if(str.equals("")){
							
							Toast.makeText(ShareSend.this, "分享的内容不能为空！", Toast.LENGTH_LONG).show();
						
						}else{
							
							OAuthV1 oa=AccessQqTokenKeeper.readQqAccessToken(ShareSend.this);
							if(oauth==null)
								oauth=new OAuthV1("null");
							oauth.setOauthConsumerKey("801351500");
							oauth.setOauthConsumerSecret("af525481caa63b51babedaaa8f1d53e5");
							try {
					        	oauth=OAuthV1Client.requestToken(oauth);
					        	oauth.setOauthToken(oa.getOauthToken());
					        	oauth.setOauthTokenSecret(oa.getOauthTokenSecret());
					        } catch (Exception e) {
					            e.printStackTrace();
					        }
							
							TAPI tApi=new TAPI(OAuthConstants.OAUTH_VERSION_1);
							try{
								tApi.add(oauth, "json", str,"192.168.0.105");
								Toast.makeText(ShareSend.this,"分享成功！", Toast.LENGTH_LONG).show();
							}catch (Exception e){
								e.printStackTrace();
							} 
							tApi.shutdownConnection();						
						}
					}
					//新浪的账号绑定了
					if(AccessSinaUserInfo.readUserInfoShareBind(ShareSend.this)){
						//send to sina
						String str=edit_share_content.getText().toString().trim();
						if(str.equals("")){
							Toast.makeText(ShareSend.this, "发布的内容不能为空！", Toast.LENGTH_SHORT).show();
						}else{
							ShareSend.accessToken=AccessSinaTokenKeeper.readSinaAccessToken(ShareSend.this);
							if(ShareSend.accessToken.isSessionValid()){
								Weibo.isWifi=Utility.isWifi(ShareSend.this);
								StatusesAPI api=new StatusesAPI(ShareSend.accessToken);
								api.update(str, "90.00", "90.00", new RequestListener() {						
		
									public void onIOException(IOException arg0) {
	
									}
									
									public void onError(WeiboException arg0) {
									}
									
									public void onComplete(String arg0) {
		
										Message msg=new Message();
										msg.what=2;
										ShareSend.this.myHandler.sendMessage(msg);
									}
								});							
							}else{
								Toast.makeText(ShareSend.this, "有效期已过，晴重新连接sina!", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		});
		
		//发布内容的编辑框中内容改变响应监听事件
		edit_share_content.addTextChangedListener(new TextWatcher() {
			
			//内容发生改变
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				//设置字体的剩余个数
				txt_send_count.setText(String.valueOf(s.toString().length())+"/240");
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
		
		//分享到Email的按钮响应事件
		btn_sharesend_email.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				/*测试中
				Intent intent = new Intent(Intent.ACTION_SEND);
				intent.putExtra(Intent.EXTRA_EMAIL, "15526886118@163.com");
				intent.putExtra(Intent.EXTRA_SUBJECT, edit_share_content.getText().toString().trim());
				intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "分享信息")); ;
				intent.setType("text/csv");
				startActivity(Intent.createChooser(intent, "Email Share"));
				*/
			}
		});
		
		//分享到短信的按钮响应事件
		btn_sharesend_sms.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				/*测试中
				Intent mIntent = new Intent();
				Uri smsToUri = Uri.parse("smsto://15526886118");			
				mIntent.putExtra("sms_body", edit_share_content.getText().toString().trim()); 
				mIntent.setType("vnd.android-dir/mmms-sms");
				mIntent.setAction(Intent.ACTION_SENDTO);
				mIntent.setData(smsToUri);
				
				//startActivity( mIntent );
				Toast.makeText(ShareSend.this, "消息发送成功！", Toast.LENGTH_SHORT).show();
				*/
			}
		});
		
		//微博图标点击绑定取消事件
		img_sharesend_qqweibo.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(AccessQqUserInfo.readQqUserShareBind(ShareSend.this)==false){
					if(AccessQqUserInfo.readQqUser(ShareSend.this).equals("-1"))
					{
						if(oauth==null)
							oauth=new OAuthV1("null");
							oauth.setOauthConsumerKey("801351500");
							oauth.setOauthConsumerSecret("af525481caa63b51babedaaa8f1d53e5");
						try {
				        	oauth=OAuthV1Client.requestToken(oauth);
				        } catch (Exception e) {
				            e.printStackTrace();
				        }
				        
			        	Intent intent = new Intent(ShareSend.this, OAuthV1AuthorizeWebView.class);
			            intent.putExtra("oauth", oauth);
			            startActivityForResult(intent,123); 
			            
					}else{
						setQqweiboMap(true);
						AccessQqUserInfo.keepQqUserShareBind(ShareSend.this, true);
					}
				}else{
					
					Dialog dlg =new AlertDialog.Builder(ShareSend.this)
						.setMessage("提示")
						.setTitle("是否取消绑定")
						.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								AccessQqUserInfo.keepQqUserShareBind(ShareSend.this, false);								
								setQqweiboMap(false);
							}
						})
						.setNegativeButton("取消", null)
						.create();
					dlg.show();	
				}
			}
		});
		
		//新浪图标点击相应事件
		img_sharesend_sina.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				CookieSyncManager.createInstance(ShareSend.this);  
				CookieSyncManager.getInstance().startSync();  
				CookieManager.getInstance().removeAllCookie();
				
				if(!AccessSinaUserInfo.readUserInfoShareBind(ShareSend.this)){
					if(AccessSinaUserInfo.readUserInfo(ShareSend.this).equals("-1")){
						mWeibo=Weibo.getInstance("1825331322", "http://www.sina.com");
						mWeibo.authorize(ShareSend.this, new SinaAuthDlgListener());
					}else{
						AccessSinaUserInfo.keepUserInfoShareBind(ShareSend.this, true);					
						setSinaMap(true);
					}
					
				}else{
					Dialog dlg =new AlertDialog.Builder(ShareSend.this)
						.setMessage("提示")
						.setTitle("是否取消绑定")
						.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								AccessSinaUserInfo.keepUserInfoShareBind(ShareSend.this, false);
								setSinaMap(false);
							}
						})
						.setNegativeButton("取消", null)
						.create();
					dlg.show();				
				}
			}
		});
	}
	
	//设置腾讯微博图标
	public void setQqweiboMap(boolean is){
		Resources rs=ShareSend.this.getResources();
		Bitmap bmp;
		if(is){
			bmp=BitmapFactory.decodeResource(rs, R.drawable.tengxun);
			
		}else{
			bmp=BitmapFactory.decodeResource(rs, R.drawable.tengxun_none);
		}
		img_sharesend_qqweibo.setImageBitmap(bmp);
	}
	
	//设置新浪图标
	public void setSinaMap(boolean is){
		Resources rs=ShareSend.this.getResources();
		Bitmap bmp;
		if(is){
			bmp=BitmapFactory.decodeResource(rs, R.drawable.sina);
			
		}else{
			bmp=BitmapFactory.decodeResource(rs, R.drawable.sina_none);
		}
		img_sharesend_sina.setImageBitmap(bmp);
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		//初始化及暂停图标的显示
		if(AccessQqUserInfo.readQqUserShareBind(ShareSend.this))
			setQqweiboMap(true);
		else
			setQqweiboMap(false);

		if(AccessSinaUserInfo.readUserInfoShareBind(ShareSend.this))
			setSinaMap(true);
		else
			setSinaMap(false);
		super.onStart();
	}
	
	
	/*
	 * 下面大部分为腾讯及新浪的用户绑定及用户名的获取信息代码，以后要重构！！！！！！！！
	 */
	public class SinaAuthDlgListener implements WeiboAuthListener{
		
		public void onComplete(Bundle values) {
			// TODO Auto-generated method stub
			String token=values.getString("access_token");
			String expires_in=values.getString("expires_in");
			ShareSend.accessToken=new Oauth2AccessToken(token,expires_in);
			if(ShareSend.accessToken.isSessionValid()){			
				AccessSinaTokenKeeper.keepSinaAccessToken(ShareSend.this, accessToken);
				
				AccountAPI accountAPI=new AccountAPI(ShareSend.accessToken);
				accountAPI.getUid(new RequestListener() {
					
					public void onIOException(IOException arg0) {
						// TODO Auto-generated method stub

					}
					
					public void onError(WeiboException arg0) {
						// TODO Auto-generated method stub

					}
					
					public void onComplete(String arg0) {
						// TODO Auto-generated method stub
						int n=arg0.indexOf(":");
						int m=arg0.indexOf("}");
						AccessSinaUserId.keepUidAccessToken(ShareSend.this, arg0.substring(n+1,m));
						Log.e("sina", arg0);
						String uid=AccessSinaUserId.readUidAccessToken(ShareSend.this);
						UsersAPI usersAPI=new UsersAPI(ShareSend.accessToken);
						Log.e("sina", uid);
						usersAPI.show(Long.parseLong(uid), new getSinaUserInfoListener());
				
					}
				});
				
			}
		}

		public void onCancel() {
			// TODO Auto-generated method stub
			
		}

		public void onError(WeiboDialogError arg0) {
			// TODO Auto-generated method stub
			Message msg=new Message();
			msg.what=4;
			ShareSend.this.myHandler.sendMessage(msg);
		}

		public void onWeiboException(WeiboException arg0) {
			// TODO Auto-generated method stub
			Message msg=new Message();
			msg.what=4;
			ShareSend.this.myHandler.sendMessage(msg);
		}
	}
	
	public class getSinaUserInfoListener implements RequestListener{

		public void onComplete(String arg0) {
			// TODO Auto-generated method stub
			int index=arg0.indexOf("screen_name");
			arg0=arg0.substring(index);
			int index2=arg0.indexOf(",");
			String name=arg0.substring(14,index2-1);
			AccessSinaUserInfo.keepUserInfo(ShareSend.this, name);		
			ShareSend.accessToken=AccessSinaTokenKeeper.readSinaAccessToken(ShareSend.this);
			
			AccessSinaUserInfo.keepUserInfoShareBind(ShareSend.this, true);			
			
			Message msg=new Message();
			msg.what=1;
			ShareSend.this.myHandler.sendMessage(msg);
		}

		public void onError(WeiboException arg0) {
			// TODO Auto-generated method stub
		}

		public void onIOException(IOException arg0) {
			// TODO Auto-generated method stub
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode==123) {
            if (resultCode==OAuthV1AuthorizeWebView.RESULT_CODE){
                oauth=(OAuthV1) data.getExtras().getSerializable("oauth");
                try {
              	  oauth=OAuthV1Client.accessToken(oauth);
                } catch (Exception e1) {
                    e1.printStackTrace();
                } 
                AccessQqTokenKeeper.keepQqAccessToken(ShareSend.this, oauth);
                Toast.makeText(ShareSend.this, "qq认证成功",Toast.LENGTH_LONG).show();
              
                UserAPI userAPI=new UserAPI(OAuthConstants.OAUTH_VERSION_1);
                   String useInfo;
				try {
					useInfo = userAPI.info(oauth, "json");
					int index=useInfo.indexOf("\"nick\"");
					useInfo=useInfo.substring(index);
					int index2=useInfo.indexOf("\",\"");
					useInfo=useInfo.substring(8,index2);
					AccessQqUserInfo.keepQqUser(ShareSend.this, useInfo);
					
					AccessQqUserInfo.keepQqUserShareBind(ShareSend.this, true);
					setQqweiboMap(true);
	            	
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
                userAPI.shutdownConnection();
                
            }else{
            	Toast.makeText(ShareSend.this, "qq认证失败",Toast.LENGTH_LONG).show();
            }
		}
	}
}
